<template>
  <div class="cart-container">
    <div class="cart-header">
      <h2>我的购物车</h2>
      <el-button type="text" @click="clearCart" v-if="cartItems.length > 0">
        清空购物车
      </el-button>
    </div>

    <div v-if="cartItems.length === 0" class="empty-cart">
      <el-empty description="购物车是空的">
        <el-button type="primary" @click="$router.push('/credit/products')">
          去购物
        </el-button>
      </el-empty>
    </div>

    <div v-else class="cart-content">
      <div class="cart-items">
        <div class="cart-item" v-for="item in cartItems" :key="item.id">
          <el-checkbox
            v-model="item.isSelected"
            @change="handleSelectChange(item)"
          />
          
          <el-image
            :src="item.product.imageUrl"
            :preview-src-list="[item.product.imageUrl]"
            fit="cover"
            class="product-image"
          />
          
          <div class="product-info">
            <h3>{{ item.product.name }}</h3>
            <p class="description">{{ item.product.description }}</p>
            <div class="price-info">
              <span class="price">¥{{ item.unitPrice }}</span>
              <span class="original-price" v-if="item.product.originalPrice">
                ¥{{ item.product.originalPrice }}
              </span>
            </div>
          </div>
          
          <div class="quantity-control">
            <el-input-number
              v-model="item.quantity"
              :min="1"
              :max="item.product.stock"
              @change="handleQuantityChange(item)"
            />
          </div>
          
          <div class="item-total">
            <span class="total-price">¥{{ item.totalPrice }}</span>
          </div>
          
          <el-button
            type="text"
            class="delete-btn"
            @click="handleDelete(item)"
          >
            删除
          </el-button>
        </div>
      </div>

      <div class="cart-summary">
        <div class="summary-item">
          <span>商品总数：</span>
          <span>{{ totalQuantity }}件</span>
        </div>
        <div class="summary-item">
          <span>商品总价：</span>
          <span class="total-price">¥{{ totalPrice }}</span>
        </div>
        <div class="summary-item" v-if="discount > 0">
          <span>优惠金额：</span>
          <span class="discount">-¥{{ discount }}</span>
        </div>
        <div class="summary-item final-price">
          <span>应付金额：</span>
          <span class="price">¥{{ finalPrice }}</span>
        </div>
        <el-button
          type="primary"
          size="large"
          :disabled="!hasSelectedItems"
          @click="handleCheckout"
        >
          结算
        </el-button>
      </div>
    </div>

    <!-- 结算对话框 -->
    <el-dialog
      v-model="checkoutDialogVisible"
      title="确认订单"
      width="600px"
    >
      <checkout-form
        :selected-items="selectedItems"
        :total-amount="finalPrice"
        @submit="handleSubmitOrder"
        @cancel="checkoutDialogVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import CheckoutForm from '@/components/credit/CheckoutForm.vue'
import { getCartItems, updateCartItemQuantity, removeCartItem, clearCart } from '@/api/cart.js'

const router = useRouter()
const cartItems = ref([])
const checkoutDialogVisible = ref(false)

// 计算属性
const selectedItems = computed(() => {
  return cartItems.value.filter(item => item.isSelected)
})

const totalQuantity = computed(() => {
  return selectedItems.value.reduce((sum, item) => sum + item.quantity, 0)
})

const totalPrice = computed(() => {
  return selectedItems.value.reduce((sum, item) => sum + item.totalPrice, 0)
})

const discount = computed(() => {
  // 根据用户信用分计算折扣
  return 0
})

const finalPrice = computed(() => {
  return totalPrice.value - discount.value
})

const hasSelectedItems = computed(() => {
  return selectedItems.value.length > 0
})

// 方法
const loadCart = async () => {
  try {
    const response = await getCartItems()
    cartItems.value = response.data
  } catch (error) {
    ElMessage.error('获取购物车数据失败')
  }
}

const handleSelectChange = async (item) => {
  try {
    await updateCartItemQuantity(item.id, { isSelected: item.isSelected })
  } catch (error) {
    ElMessage.error('更新选中状态失败')
    item.isSelected = !item.isSelected
  }
}

const handleQuantityChange = async (item) => {
  try {
    await updateCartItemQuantity(item.id, { quantity: item.quantity })
  } catch (error) {
    ElMessage.error('更新数量失败')
    await loadCart()
  }
}

const handleDelete = async (item) => {
  try {
    await ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
      type: 'warning'
    })
    await removeCartItem(item.id)
    await loadCart()
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleClearCart = async () => {
  try {
    await ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
      type: 'warning'
    })
    await clearCart()
    cartItems.value = []
    ElMessage.success('购物车已清空')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('清空购物车失败')
    }
  }
}

const handleCheckout = () => {
  checkoutDialogVisible.value = true
}

const handleSubmitOrder = async (orderData) => {
  try {
    // 处理订单提交
    checkoutDialogVisible.value = false
    router.push('/credit/orders')
  } catch (error) {
    ElMessage.error('提交订单失败')
  }
}

onMounted(() => {
  loadCart()
})
</script>

<style lang="scss" scoped>
.cart-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);

  .cart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 24px;
      color: #303133;
    }
  }

  .empty-cart {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 400px;
    background-color: #fff;
    border-radius: 4px;
  }

  .cart-content {
    display: flex;
    gap: 20px;

    .cart-items {
      flex: 1;
      background-color: #fff;
      border-radius: 4px;
      padding: 20px;

      .cart-item {
        display: flex;
        align-items: center;
        padding: 20px 0;
        border-bottom: 1px solid #ebeef5;

        &:last-child {
          border-bottom: none;
        }

        .product-image {
          width: 100px;
          height: 100px;
          margin: 0 20px;
          border-radius: 4px;
        }

        .product-info {
          flex: 1;

          h3 {
            margin: 0 0 10px;
            font-size: 16px;
            color: #303133;
          }

          .description {
            color: #909399;
            font-size: 14px;
            margin-bottom: 10px;
          }

          .price-info {
            .price {
              color: #f56c6c;
              font-size: 18px;
              font-weight: bold;
            }

            .original-price {
              color: #909399;
              text-decoration: line-through;
              margin-left: 10px;
            }
          }
        }

        .quantity-control {
          margin: 0 20px;
        }

        .item-total {
          width: 120px;
          text-align: right;

          .total-price {
            color: #f56c6c;
            font-size: 18px;
            font-weight: bold;
          }
        }

        .delete-btn {
          margin-left: 20px;
        }
      }
    }

    .cart-summary {
      width: 300px;
      background-color: #fff;
      border-radius: 4px;
      padding: 20px;

      .summary-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 15px;
        color: #606266;

        &.final-price {
          margin-top: 20px;
          padding-top: 20px;
          border-top: 1px solid #ebeef5;
          font-size: 18px;
          color: #303133;

          .price {
            color: #f56c6c;
            font-weight: bold;
          }
        }

        .discount {
          color: #67c23a;
        }
      }

      .el-button {
        width: 100%;
        margin-top: 20px;
      }
    }
  }
}
</style> 